package com.gks.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gks.entities.Blog;
import com.gks.mapper.BlogMapper;
import com.gks.service.BlogService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class BlogServiceImpl implements BlogService {
    
    @Resource
    private BlogMapper blogMapper;

    @Override
    public List<Blog> getAllBlogs() {
        return blogMapper.selectList(null);
    }

    @Override
    public Page<Blog> getBlogsByPage(int pageNum, int pageSize) {
        Page<Blog> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        
        return blogMapper.selectPage(page, queryWrapper);
    }

    @Override
    public Blog getBlogById(Long id) {
        return blogMapper.selectById(id);
    }

    @Override
    public Blog createBlog(Blog blog) {
        blog.setCreateTime(new Date());
        blog.setUpdateTime(new Date());
        
        blogMapper.insert(blog);
        return blog;
    }

    @Override
    public Blog updateBlog(Blog blog) {
        Blog existingBlog = blogMapper.selectById(blog.getId());
        if (existingBlog == null) {
            throw new RuntimeException("博客不存在");
        }
        
        blog.setUpdateTime(new Date());
        blogMapper.updateById(blog);
        return blog;
    }

    @Override
    public void deleteBlog(Long id) {
        Blog existingBlog = blogMapper.selectById(id);
        if (existingBlog == null) {
            throw new RuntimeException("博客不存在");
        }
        
        blogMapper.deleteById(id);
    }
}
